package cn.wyl.basic.controller;

import cn.wyl.basic.util.AxiousResult;
import cn.wyl.basic.util.FastDfsUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@RestController
@RequestMapping("/fastDfs")
public class FastDfscontroller {
    //@RequestPart对复杂表单项的处理，前端默认发送post请求，默认前端传来的参数name="file",与上传文件的name属性值一致
    @PostMapping
    public AxiousResult upload(@RequestPart(required = true,value = "file")MultipartFile file){
        // 上传文件到服务器 String upload(byte[] file,String extName) 返回值：/group1/M00/00/F5/CgAIC2LdNKmASWeAAALwDkFK6wU183.jpg
        try {
            String originalFilename = file.getOriginalFilename();
            int suffixIndex = originalFilename.lastIndexOf(".") + 1;
            //文件后缀名
            String extName = originalFilename.substring(suffixIndex);
            //利用FastDfsUtils上传文件到服务器
            String filePath = FastDfsUtils.upload(file.getBytes(), extName);

            //上传成功
            AxiousResult axiousResult = new AxiousResult();
            axiousResult.setResultObj(filePath);

            //返回AxiousResult对象，resutObj属性包含了文件路径
            return axiousResult;
        } catch (IOException e) {
            e.printStackTrace();
            return  new AxiousResult(false,"文件上传失败"+e.getMessage(),null);
        }
    }

    //  "/fastDfs/?path="+filePath 前端传的filePath类似/group1/M00/00/F6/CgAIC2LdPLKALjbnAASpeRG4aog727.png
    // 调用FastDfsUtils的方法： void delete(String groupName,String fileName)
    //  required = true 必须提供path=filePath
    @DeleteMapping
    public AxiousResult del(@RequestParam(required = true,value = "path") String  path){
        try {
           // System.out.println(path);
            String pathTmp = path.substring(1); //  group1/M00/00/F6/CgAIC2LdPLKALjbnAASpeRG4aog727.png
            String groupName = pathTmp.substring(0, pathTmp.indexOf("/"));// group1
            String fileName = pathTmp.substring(pathTmp.indexOf("/") + 1);// M00/00/F6/CgAIC2LdPLKALjbnAASpeRG4aog727.png
            //利用FastDfsUtils从服务器删除文件
            FastDfsUtils.delete(groupName,fileName);
            return new AxiousResult();
        } catch (Exception e) {
            e.printStackTrace();
            return  new AxiousResult(false,"删除失败"+e.getMessage(),null);
        }



    }
}
